<template>
  <div class="main_box">
    <el-row class="header-row">
      <el-col>
        <div class="search_wrap">
          <el-form :inline="true" :model="filters" class="demo-form-inline" ref="searchForm">
            <el-form-item prop="villAreaName">
              <el-input v-model="filters.villAreaName" clearable placeholder="地区名称"></el-input>
            </el-form-item>
            <el-form-item prop="villAreaCode">
              <el-input v-model="filters.villAreaCode" clearable placeholder="地区编号"></el-input>
            </el-form-item>
            <el-form-item prop="villageId">
              <el-select v-model="filters.villageId" clearable filterable placeholder="请选择小区">
                <el-option v-for="item in villageList" :value="item.id" :label="item.name" :key="item.id"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button icon="el-icon-search" type="primary" @click="onSearch">查询 </el-button>
              <el-button icon="el-icon-refresh-left" @click="resetForm">重置 </el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-col>
      <el-col>
        <div class="opration_wrap">
          <el-tooltip content="刷新" placement="top">
            <el-button circle icon="el-icon-refresh-right" @click="reload" size="mini"></el-button>
          </el-tooltip>
          <div>
            <el-button type="primary" plain icon="fa fa-plus" v-has="permissionAdd" @click="handleClickAdd()" size="mini"> 新增 </el-button>
            <el-button type="success" plain icon="el-icon-folder-opened" v-has="permissionImport" @click="handleImportList()" size="mini"> 导入栋单元层 </el-button>
            <el-button type="warning" plain icon="fa fa-plus" v-has="permissionChannel" @click="handleClickChannel()" size="mini"> 批量上传通道 </el-button>
            <el-button type="danger" icon="el-icon-delete" v-has="permissionBatchDelete" @click="handleClickBatchDelete()" size="mini">批量删除</el-button>
          </div>
        </div>
      </el-col>
    </el-row>

    <el-row ref="tableRow">
      <!-- 列表 -->
      <tree-table
        v-loading="listLoading"
        :tableHeight="'750px'"
        id="scrollDiv"
        ref="tableRow1"
        :props="{ isLeaf: 'leaf' }"
        @load="handleLoadLazyTree"
        lazy
        :columns="columns"
        :data="treeTableList"
        :eval-func="func"
        :selection="true"
        element-loading-text="数据加载中，请稍后..."
        empty-text="对不起，没有找到相关数据！"
        @multipleSelection="multipleId"
      >
        <el-table-column label="小区" prop="villageName" align="center"></el-table-column>
        <el-table-column align="center" label="地区id" prop="id"> </el-table-column>
        <el-table-column align="center" label="地区编号" prop="villAreaCode"> </el-table-column>

        <el-table-column label="地区层级">
          <template slot-scope="{ row }">
            <div>
              {{ formatLevel(row.level) }}
            </div>
          </template>
        </el-table-column>

        <el-table-column label="排序" prop="sort" align="center" width="100"></el-table-column>
        <el-table-column align="center" label="创建时间" prop="createDate"> </el-table-column>
        <el-table-column label="操作" width="136" fixed="right">
          <template slot-scope="scope">
            <el-button v-has="permissionCheck" @click="handleClickDetail(scope.row)" size="mini">查看 </el-button>
            <el-dropdown trigger="click" size="small">
              <el-button type="primary"> <i class="fa fa-list-ul"></i>更多 </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item v-has="permissionAdd" @click.native="handleClickAdd(scope.row)" v-if="scope.row.level < 4">新增 </el-dropdown-item>
                <el-dropdown-item v-has="permissionEdit" @click.native="handleClickEditor(scope.row)">编辑 </el-dropdown-item>
                <!-- <el-dropdown-item v-has="permissionUpStatus" @click.native="handleIsDisable(scope.row)">{{scope.row.state === 0? '启用' : '禁用'}}</el-dropdown-item> -->
                <el-dropdown-item v-has="permissionDelete" @click.native="handleClickDelete(scope.row)">删除 </el-dropdown-item>
                <el-dropdown-item v-has="permissionChannel" @click.native="handleClickChannel(scope.row)">上传通道 </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </tree-table>

      <!-- 分页工具条 -->
      <!-- <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page.pageNo"
          :page-sizes="[20, 50, 100]"
          :page-size="page.pageSize"
          layout="total, sizes, jumper, next, pager, prev"
          :total="page.pageTotal"
        ></el-pagination> -->
    </el-row>

    <!-- 导入栋单元层 -->
    <el-dialog title="导入栋单元层" :visible.sync="importList.show" width="fit-content" center :close-on-click-modal="false">
      <div style="margin: 50px 100px">
        <el-upload :class="['upload', importList.file ? '' : 'no-file']" action="#" :auto-upload="false" :on-change="getImportListFile" accept=".xls,.xlsx" :show-file-list="false">
          <i v-if="!importList.file" class="el-icon-plus"></i>
          <div class="excel-file" v-else>
            <img src="/src/assets/img/excel.png" alt="" />
            <div>
              {{ importList.file.name }}
            </div>
          </div>
        </el-upload>
        <div style="margin-top: 4px">
          <a style="color: red; text-decoration: none" :href="importList.importListModule"> 下载导入模板 </a>
        </div>
      </div>
      <div slot="footer">
        <el-button @click="confirmImportList" type="primary">确定</el-button>
        <el-button @click="importList.show = false">取消</el-button>
      </div>
    </el-dialog>

    <ChannelEntrySet :idArr="ids" type="2" @handleClose="channelClose" @handleConfirm="channelConfirm" :channelShow="channelShow"></ChannelEntrySet>
  </div>
</template>
<script>
import VillageAreaApi from '@/api/address/villageArea';
import VillageApi from '@/api/address/village';
import * as message from '@/constants/message';
import TreeTable from '@/components/TreeTable';
import treeToArray from '@/utils/customEval';
import uploadOssFn from '@/utils/uploadOssFn';
import { VILLAGEAREA_IMPORT } from '@/constants/constants';
import ChannelEntrySet from '@/components/ChannelEntrySet.vue';
import { filter } from 'lodash-es';

export default {
  name: 'VillageAreaManagement',
  inject: ['reload'], //注入局部刷新
  data() {
    return {
      ids: [],
      channelShow: false,
      dataList: [],
      listLoading: false,
      columns: [
        {
          text: '地区名称',
          value: 'name',
          width: 300,
          align: 'left',
        },
      ],
      treeTableList: [],
      func: treeToArray, // 从树形结构转为数组
      expandAll: false, // 是否展开
      //开始切割的位置
      starSize: 0,
      //结束位置
      endSize: 20,
      totalSize: [],
      filters: {
        villAreaName: '',
        villAreaCode: '',
        level: '',
        villageId: '',
      },
      page: {
        pageNo: 1,
        pageTotal: 0,
        pageSize: 100,
      },
      villageAreaLevelList: [
        { id: 1, name: '栋' },
        { id: 2, name: '单元' },
        { id: 3, name: '层' },
      ],
      villageList: [],
      importList: {
        show: false,
        file: '',
        importListModule: VILLAGEAREA_IMPORT,
      },

      permissionAdd: 'SYSTEM_MANAGER_ADDRESS_VILLAGE_AREA_LIST_ADD',
      permissionCheck: 'SYSTEM_MANAGER_ADDRESS_VILLAGE_AREA_LIST_SEE',
      permissionEdit: 'SYSTEM_MANAGER_ADDRESS_VILLAGE_AREA_LIST_EDIT',
      permissionDelete: 'SYSTEM_MANAGER_ADDRESS_VILLAGE_AREA_LIST_DELETE',
      permissionImport: 'SYSTEM_MANAGER_ADDRESS_VILLAGE_AREA_LIST_IMPORT',
      permissionChannel: 'SYSTEM_MANAGER_ADDRESS_VILLAGE_AREA_LIST_CHANNEL',
      permissionBatchDelete: 'SYSTEM_MANAGER_ADDRESS_VILLAGE_AREA_LIST_BATCH_DELETE',
    };
  },
  mounted() {
    this.init();
    window.addEventListener('keydown', this.keyDown);
  },
  components: {
    TreeTable,
    ChannelEntrySet,
  },
  activated() {
    this.listData();
  },
  destroyed() {
    window.removeEventListener('keydown', this.keyDown, false);
  },
  methods: {
    multipleId(e) {
      this.ids = e.map((item) => item.id);
    },
    channelClose(e) {
      this.channelShow = e;
    },
    channelConfirm(e) {
      this.channelShow = e;
      this.ids = [];
      this.init();
    },
    handleClickChannel(e) {
      if (e) {
        this.ids = [];
        this.$refs.tableRow1.$children[0].clearSelection();
        this.$refs.tableRow1.$children[0].toggleRowSelection(e, true);
        if (!this.ids.includes(e.id)) {
          this.ids.push(e.id);
        }
      }
      if (this.ids.length === 0) {
        this.$message.error('请至少选择一项');
        return false;
      }
      this.channelShow = true;
    },

    init() {
      this.getVillageList();
      this.getTableHeight();
    },
    keyDown(e) {
      //如果是回车则执行查询方法
      if (e.keyCode === 13) {
        this.onSearch();
      }
    },
    //懒加载1-节流函数
    throttle(fn, delay) {
      let valid = true;
      return function () {
        if (!valid) {
          //休息时间 暂不执行
          return false;
        }
        // 工作时间，执行函数并且在间隔期内把状态位设为无效
        valid = false;
        setTimeout(() => {
          fn();
          valid = true;
        }, delay);
      };
    },
    //懒加载2-触发方法
    triggerScroll() {
      document.querySelector('#scrollDiv .el-table__body-wrapper').addEventListener('scroll', this.throttle(this.handleScroll, 1000));
    },
    //懒加载3-主体方法
    handleScroll() {
      let scrollTop = document.querySelector('#scrollDiv .el-table__body-wrapper').scrollTop;
      let scrollHeight = document.querySelector('#scrollDiv .el-table__body-wrapper').scrollHeight;
      let clientHeight = document.querySelector('#scrollDiv .el-table__body-wrapper').clientHeight;
      if (this.totalSize.length === this.treeTableList.length) {
        //表示已到底部
        return;
      }
      if (scrollHeight - clientHeight - scrollTop < 30) {
        //监听滚动条到底部
        this.starSize = this.starSize + 20;
        this.endSize = this.endSize + 20;
        let arrOne = this.treeTableList;
        let arrTwo = this.totalSize.slice(this.starSize, this.endSize);
        this.treeTableList = arrOne.concat(arrTwo);
      }
    },
    getTableHeight() {
      this.$nextTick(function () {
        this.maxHeight = window.innerHeight - this.$refs.tableRow1.$el.offsetTop - 50;
        window.onresize = () => {
          this.maxHeight = window.innerHeight - this.$refs.tableRow1.$el.offsetTop - 50;
        };
      });
    },
    async getVillageList() {
      const { data } = await VillageApi.villageList();
      this.villageList = data || [];
    },
    formatLevel(cellValue) {
      if (cellValue === 1) {
        return '栋';
      } else if (cellValue === 2) {
        return '单元';
      } else if (cellValue === 3) {
        return '层';
      } else if (cellValue === 4) {
        return '门牌号';
      }
    },
    formatState(cellValue) {
      if (cellValue === -1) {
        return '删除';
      } else if (cellValue === 0) {
        return '禁用';
      } else if (cellValue === 1) {
        return '启用';
      }
    },
    formatStates(cellValue) {
      if (cellValue === -1) {
        return 'danger';
      } else if (cellValue === 0) {
        return 'info';
      } else if (cellValue === 1) {
        return 'success';
      }
    },
    formatVillageAreaType(cellValue) {
      if (cellValue === 1) {
        return '住家';
      } else if (cellValue === 2) {
        return '办公';
      }
    },
    // 导入栋单元层
    handleImportList() {
      if (!this.filters.villageId) return this.$message.error('请选择小区');
      this.importList.show = true;
      this.importList.file = '';
    },
    // 获取导入列表文件
    async getImportListFile(file) {
      this.importList.file = file;
    },
    // 确定导入栋单元层
    async confirmImportList() {
      const {
        filters: { villageId },
        importList: { file },
      } = this;
      if (!villageId) return this.$message.error('请选择小区');
      if (!file) return this.$message.error('请导入文件');
      const params = {
        villageId,
        url: (await uploadOssFn([file]))[0].url,
      };
      await VillageAreaApi.importVArea(params);
      this.page.pageNo = 1;
      this.listData();
      this.$message.success('导入成功');
      this.importList.show = false;
    },
    handleSizeChange(size) {
      let _this = this;
      _this.page.pageSize = size;
      _this.listData();
    },
    handleCurrentChange(val) {
      let _this = this;
      _this.page.pageNo = val;
      _this.listData();
    },
    handleClickAdd(row) {
      let path = `/address/villageAreaAdd`;
      if (row) {
        let arr = [];
        arr = this.$Utils.filterTreeToArr(this.treeTableList, row, 'id');
        arr = arr.map((item) => item.name).join('/');
        path = `${path}?level=${row.level + 1}&parentId=${row.id}&parentNames=${arr}`;
      } else {
        path = `${path}?level=1`;
      }
      const { villageId } = this.filters;
      villageId && (path = `${path}&villageId=${villageId}`);
      this.$router.push(path);
    },
    handleClickEditor({ level, id }) {
      let path = `/address/villageAreaEdit?id=${id}`;
      if (level > 1) {
        let arr = this.$Utils.filterTreeToArr(this.treeTableList, { id }, 'id');
        arr.pop();
        arr = arr.map((item) => item.name).join('/');
        path = `${path}&parentNames=${arr}`;
      }

      this.$router.push(path);
    },
    handleClickDetail(row) {
      const { level, villageId, id } = row;
      let path = '';
      if (!row.level) {
        path = `/address/villageDetail?id=${villageId}`;
      } else {
        path = `/address/villageAreaDetail?id=${id}`;
      }
      // if(level)

      // let path = `/address/villageAreaDetail?id=${row.id}`
      // if(row.level>1){
      //   let arr = this.$Utils.filterTreeToArr(this.treeTableList,row,'id')
      //   arr.pop()
      //   arr = arr.map(item=>item.name).join("/")
      //   path = `${path}&parentNames=${arr}`
      // }
      this.$router.push(path);
    },
    handleIsDisable(row) {
      let _this = this;
      let currentState = row.state === 0 ? 1 : 0;
      this.$confirm(currentState ? '是否启用？' : '是否禁用', message.TITLE_PROMPT, {}).then(() => {
        VillageAreaApi.deleteVillageArea({
          id: row.id,
          state: currentState,
        }).then((res) => {
          this.$Utils.notifySuccess();
          _this.listData();
        });
      });
    },
    handleClickDelete(val) {
      let _this = this;
      _this.$confirm(message.MSG_CONFIRM_DELETE, message.TITLE_PROMPT, {}).then(() => {
        VillageAreaApi.deleteVillageArea({
          id: val.id,
          state: -1,
        }).then((res) => {
          this.$Utils.notifySuccess();
          _this.listData();
        });
      });
    },
    handleClickBatchDelete() {
      if (this.ids.length === 0) {
        this.$message.error('请选择栋单元层');
        return false;
      }
      this.$confirm('是否批量删除栋单元层', message.TITLE_PROMPT, {}).then(() => {
        let param = { ids: this.ids, state: 1 };
        VillageAreaApi.batchDelete(param).then((res) => {
          this.$Utils.notifySuccess();
          this.listData();
        });
      });
    },
    resetForm() {
      this.$refs.searchForm.resetFields();
      this.onSearch()
    },
    onSearch() {
      this.page.pageNo = 1;
      this.listData();
    },
    listData() {
      this.totalSize = [];
      this.treeTableList = [];
      this.starSize = 0;
      this.endSize = 20;
      // 获取列表数据
      const {
        filters: { villAreaName, villAreaCode, villageId },
      } = this;
      if (!villageId) {
        this.$message.error('请先选择小区');
        return;
      }
      let cond = { villAreaName, villAreaCode, villageId, level: -2 };
      this.listLoading = true;
      VillageAreaApi.listVillageArea(cond)
        .then((res) => {
          this.totalSize = res.data;
          this.treeTableList = this.totalSize;
          this.listLoading = false;
        })
        .catch((err) => {
          this.listLoading = false;
        });
    },

    /**
     * 懒加载树
     * @param node
     */
    handleLoadLazyTree(node) {
      const {
        filters: { villAreaName, villAreaCode, villageId },
      } = this;
      if (!villageId) {
        this.$message.error('请先选择小区');
        return;
      }
      if (node.level !== 1) return;
      this.listLoading = true;
      VillageAreaApi.listVillageArea({ villAreaName, villAreaCode, villageId, parentId: node.id })
        .then((res) => {
          const index = this.treeTableList.findIndex((c) => c.id === node.id);
          this.treeTableList[index].children = res.data;
          this.listLoading = false;
        })
        .catch((err) => {
          this.listLoading = false;
        });
    },
  },
};
</script>
<style lang="scss">
@import '@/assets/css/views/content.scss';
</style>
<style lang="scss" scoped>
.upload {
  .el-icon-plus {
    font-size: 30px;
  }

  .excel-file {
    text-align: center;
    height: 100px;

    img {
      width: 100px;
    }
  }
}

.no-file {
  &::v-deep .el-upload {
    height: 150px;
    width: 150px;
    display: flex;
    align-items: center;
    justify-content: space-around;
    border: 1px rgb(160, 160, 160) dashed;
    border-radius: 4px;

    &:hover {
      border-color: black;
    }
  }
}
</style>
